package com.hn.zhijian.base.common.exception;

import com.hn.zhijian.base.common.StatusCode;
import com.hn.zhijian.base.model.response.Response;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author carl chen
 * @Classname EXcptionHandler
 * @Description 统一异常处理
 * @Date 2019/10/30 13:37
 */
@ControllerAdvice
@ConfigurationProperties(prefix = "exception")
@Slf4j
@Data
public class ExceptionHandlerResolver {

    /**
     * 调试开关
     */
    private boolean debug;

    /**
     * 统一处理异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Response handleException(Exception exception) throws Exception {
        if (!debug) {
            exception.printStackTrace();
        }
        Response resultModel = null;
        if (exception instanceof ApplicationException) {
            //业务服务异常
            ApplicationException e = (ApplicationException) exception;
            resultModel = new Response(e.getCode(), e.getMessage());
        } else if (exception instanceof DataIntegrityViolationException) {
            //服务器内部错误
            resultModel = new Response(StatusCode.DATA_INTEGRITY_VIOLATION_EXCEPTION.getCode(), exception.getMessage());
        } else if (exception instanceof NoHandlerFoundException) {
            //404异常
            resultModel = new Response(StatusCode.NOT_FOUND.getCode(), StatusCode.NOT_FOUND.getMessage());
        } else if (exception instanceof HttpRequestMethodNotSupportedException) {
            //405
            resultModel = new Response(HttpStatus.METHOD_NOT_ALLOWED.value(), HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
        } else if (exception instanceof MethodArgumentTypeMismatchException) {
            //参数转换错误
            resultModel = new Response(StatusCode.PARAM_ERR.getCode(), StatusCode.PARAM_ERR.getMessage());
        } else if (exception instanceof NoHandlerFoundException) {
            //400
            resultModel = new Response(HttpStatus.METHOD_NOT_ALLOWED.value(), HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
        } else {
            //服务器内部错误
            resultModel = new Response(StatusCode.SERVER_ERROR.getCode(), exception.getMessage());
        }
        log.debug(resultModel.getCode() + "", resultModel.getMessage());
        //错误消息还是需要打印在控制台

        return resultModel;
    }
}
